<template>
  <BasicInformation :title="title" @action="handleAction" :primary-actions="mainActions"></BasicInformation>

  <div class="add">
    <div class="common-layout">
      <el-container>
        <el-main>
          <el-row>
            <el-col :span="24">
              <div class="grid-content ep-bg-purple">
                <h4>基本信息</h4>
                <el-form :inline="true" :model="outStoreOrder" :rules="rules" status-icon ref="formRef">
                  <el-form-item label="单据编号" prop="code">
                    <el-input
                        v-model="outStoreOrder.code"
                        style="width: 240px"
                        placeholder="请输入单据编号"
                        clearable
                        :disabled="true"
                    />
                  </el-form-item>
                  <!-- 客户 -->
                  <el-form-item label="客户" prop="cid">
                    <el-select
                        v-model="outStoreOrder.cid"
                        placeholder="请选择客户"
                        style="width: 240px"
                        clearable
                        filterable
                    >
                      <el-option
                          v-for="customer in customerList"
                          :key="customer.id"
                          :label="`${customer.code} - ${customer.name}`"
                          :value="customer.id"
                      />
                    </el-select>
                  </el-form-item>

                  <!-- 报价日期 -->
                  <el-form-item label="单据日期" prop="orderDate">
                    <el-date-picker
                        v-model="outStoreOrder.orderDate"
                        type="date"
                        placeholder="请选择日期"
                        value-format="YYYY-MM-DD"
                        :disabled-date="disabledDate"
                    />
                  </el-form-item>
                  <!-- 业务员 -->
                  <el-form-item label="业务员" prop="businessmanId">

                    <el-select
                        v-model="outStoreOrder.businessmanId"
                        placeholder="请选择业务员"
                        style="width: 240px"
                        clearable
                        filterable
                    >
                      <el-option
                          v-for="user in userList"
                          :key="user.id"
                          :label="`${user.name}`"
                          :value="user.id"
                      />
                    </el-select>

                  </el-form-item>

                  <!-- 库管员 -->
                  <el-form-item label="库管员" prop="storeManId">

                    <el-select
                        v-model="outStoreOrder.storeManId"
                        placeholder="请选择库管员"
                        style="width: 240px"
                        clearable
                        filterable
                    >
                      <el-option
                          v-for="user in userList"
                          :key="user.id"
                          :label="`${user.name}`"
                          :value="user.id"
                      />
                    </el-select>

                  </el-form-item>

                  <!-- 部门 -->
                  <el-form-item label="部门" prop="deptId">
                    <el-select
                        v-model="outStoreOrder.deptId"
                        placeholder="请选择部门"
                        style="width: 240px;"
                        clearable
                    >
                      <el-option
                          v-for="dept in deptList"
                          :key="dept.id"
                          :label="dept.name"
                          :value="dept.id"
                      />
                    </el-select>
                  </el-form-item>
                </el-form>
              </div>
            </el-col>
          </el-row>
        </el-main>
      </el-container>
    </div>
  </div>
  <div>
    <div class="toolbar">
      <el-button type="primary">商品信息</el-button>
      <el-button @click="addDetailRow">继续添加</el-button>
      <el-button type="danger" @click="deleteSelectedRows">删除选中行</el-button>
    </div>

    <!-- 商品信息表格 -->
    <el-table :data="OutStoreDetail" border style="width: 100%" class="goods-table" @selection-change="newHHandleSelectionChange">
      <el-table-column type="selection" width="55" />
      <!-- 商品编码（带必填标识的下拉框） -->
      <el-table-column label="商品编码" width="150">
        <template #header>
          <span class="required-label">商品编码</span>
        </template>
        <template #default="scope">
          <el-select
              v-model="scope.row.goodsCode"
              placeholder="请选择商品"
              @change="handleGoodsChange(scope.row)"
              clearable
          >
            <el-option
                v-for="item in goodsList"
                :key="item.code"
                :label="`${item.code} - ${item.name}`"
                :value="item.code"
            />
          </el-select>
        </template>
      </el-table-column>

      <!-- 商品名称 -->
      <el-table-column label="商品名称" width="180">
        <template #default="scope">{{ scope.row.goodsName || '-' }}</template>
      </el-table-column>


      <!-- 商品规格 -->
      <el-table-column label="商品规格" width="120" align="center">
        <template #default="scope">{{ scope.row.goodsType || '' }}</template>
      </el-table-column>


      <!-- 仓库信息（带必填标识的下拉框） -->
      <el-table-column label="仓库" width="150">
        <template #header>
          <span class="required-label">仓库</span>
        </template>
        <template #default="scope">
          <el-select
              @change ="storeChange(scope.row)"
              v-model="scope.row.storeId"
              placeholder="请选择仓库"
              clearable
          >
            <el-option
                v-for="store in storeList"
                :key="store.id"
                :label="`${store.code} - ${store.name}`"
                :value="store.id"
            />
          </el-select>
        </template>
      </el-table-column>

      <!-- 即时库存 -->
      <el-table-column label="即时库存" width="100" align="center">
        <template #default="scope">{{ scope.row.stock || 0 }}</template>
      </el-table-column>

      <!-- 单位（带必填标识） -->
      <el-table-column label="单位" width="80" align="center">
        <template #header>
          <span class="required-label">单位</span>
        </template>
        <template #default="scope">{{ scope.row.unit || '件' }}</template>
      </el-table-column>

      <!-- 数量（带必填标识的输入框） -->
      <el-table-column label="数量" width="120" align="center">
        <template #header>
          <span class="required-label">数量</span>
        </template>
        <template #default="scope">
          <el-input-number
              v-model="scope.row.count"
              @change="changeNum(scope.row)"
              controls-position="right"
              style="width: 100px"
          >
          </el-input-number>
        </template>
      </el-table-column>




      <!-- 数量（带必填标识的输入框） -->
      <el-table-column label="单价" width="120" align="center">
        <template #header>
          <span class="required-label">单价</span>
        </template>
        <template #default="scope">
          <el-input-number
              v-model="scope.row.price"
              @change="changePrice(scope.row)"
              controls-position="right"
              style="width: 100px"
          >
          </el-input-number>
        </template>
      </el-table-column>



      <el-table-column label="总价" width="120" align="center">
        <template #default="scope">{{ scope.row.sumPrice || 0 }}</template>
      </el-table-column>



      <el-table-column label="税率" width="120" align="center">
        <template #default="scope">{{ scope.row.tax || 0 }}</template>
      </el-table-column>



      <el-table-column label="含税单价" width="120" align="center">
        <template #default="scope">{{ scope.row.taxSinglePrice || 0 }}</template>
      </el-table-column>

      <el-table-column label="含税总价" width="120" align="center">
        <template #default="scope">{{ scope.row.taxSumPrice || 0 }}</template>
      </el-table-column>

      <el-table-column label="单位成本" width="120" align="center">
        <template #default="scope">{{ scope.row.outStoreSingleCost || 0 }}</template>
      </el-table-column>


      <el-table-column label="总成本" width="120" align="center">
        <template #default="scope">{{ scope.row.outStoreSumCost || 0 }}</template>
      </el-table-column>
    </el-table>

  </div>
  <div class="total-summary">
    <div class="total-label">合计</div>
    <div class="total-amount">{{ formatTotal }}</div>
  </div>



</template>



<script setup lang="ts">
import {ref, reactive, withKeys, watch, computed, onMounted, type UnwrapRef} from 'vue';
import BasicInformation from '@/public-view/BasicInformation.vue';
import type {ComponentSize, FormInstance, FormRules} from 'element-plus'
import {ElInput, ElAutoResizer, ElTableV2} from 'element-plus'
import type {FunctionalComponent} from 'vue'
import type {Column, InputInstance} from 'element-plus'
import {useRouter, useRoute, type RouteParamValue} from 'vue-router';
import type { SalesQuotation } from '@/types/public-xs/salesDocuments';
import type { SalesOrder } from '@/types/public-xs/salesDocuments';
import type { Goods } from '@/types/public-xs/Goods';
import type { SalesQuotationDetail } from '@/types/public-xs/salesDocuments';
import type { Customer } from '@/types/public-xs/Customer';
import axios from 'axios';
import { ElMessageBox, ElMessage } from 'element-plus'
import type { SalesOrderDetail } from '@/types/public-xs/salesDocuments';
import type {PublicProvider} from "@/types/public-cg/provider.ts";
import type {User} from "@/types/rs/User.ts";
import type {Department} from "@/types/rs/Department.ts";
import type {Store} from "@/types/basic/store.ts";
import request from "@/util/request.ts";

let route=useRoute()

let sourceCode=ref('')
let title=ref('其他出库单')
let goodsList=ref<Goods[]>([])
let pageNo=ref(1)
let pageSize=ref(3)
let allPage=ref(0)
let router=useRouter()
let handlePageChange = ()=>{

}
//部门情况

//商品查询条件
const queryConditions = reactive({
  combine: '',
  kid: ''
})


//填写信息区域的表单验证
const rules = reactive({
  cid: [{ required: true, message: '请选择客户', trigger: 'blur' ,type:'number'}],
  code: [{ required: true, message: '请填写单据编号', trigger: 'change' }],
  businessmanId: [{ required: true, message: '请选择业务员', trigger: 'blur' }],
  storeManId: [{ required: true, message: '请选择库管员', trigger: 'blur' }],
  deptId: [{ required: true, message: '请选择部门', trigger: 'change' }]
})
const disabledDate = (time: Date) => {
  return time.getTime() > Date.now()
}

// 操作的方法具体执行
const handleAction = (action:string) => {
  switch(action) {
    case 'choose':

      break
    case 'save-add':
      insertOutStoreOrder()
      break;
    case 'history':
      router.push('/home/outStore/otherOutStore/page')
      break;
  }
}

//商品显示
async function fetchData(page: number) {
  try {
    const params = new URLSearchParams();
    params.append('pageNow', page.toString());
    params.append('pageSize', 100);
    params.append('combine', queryConditions.combine);
    params.append('kid', queryConditions.kid);

    let response = await request.post('basic/good/getGoodPage', params, {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    });
    goodsList.value = response.data.data.list.map((item: any) => ({
      id: item.id,
      code: item.code,
      name: item.name,
      unique: item.unique,
      tax: item.tax,
      stock: item.stock,
      kname: item.kname
    }));
    console.log(goodsList.value)
    allPage.value = response.data.data.total || 0;
  } catch (error) {
    ElMessage.error('获取商品数据失败');
    OutStoreDetail.value = [];
    allPage.value = 0;
    console.error('获取数据失败:', error);
  }
}
fetchData(1)

const storeChange = async (row:any) => {

  let response = await request.get('kc/StoreGoodSummary/selectKcStoreGoodBySidCid', {
    params:{
      sid: row.storeId,
      gid: row.goodId
    },
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    }
  })
  console.log(response.data.data)
  if (response.data.data) {
    row.stock = response.data.data.stock
    row.singleCost = response.data.data.singleCost
  }else{
    row.stock = 0
    row.singleCost = 0
  }
  changeNum(row)
}

//左上角按钮

const mainActions = ref([
  {
    name: 'save',
    label: '保存',
    type: 'primary',
    icon: 'DocumentAdd'
  },
  {
    name: 'save-add',
    label: '保存修改',
    disabled: false
  },
  {
    name: 'audit',
    label: '审核',
    hidden: false
  },
  {
    name: 'choose',
    label: '选择源单',
    hidden: false
  },
  {
    name: 'history',
    label: '历史单据',
    badge: 3 // 角标数字
  }
])

//出库单
let outStoreOrder=ref({
  id:null,
  code:'',
  orderDate:new Date,
  sourceCode:sourceCode.value,
  cid: null,
  businessmanId: null,
  deptId:null,
  orderStatus: 0,
  storeManId:null,
  orderTypeId:0,
  typeId:6,
  outStoreSumPrice:0,
  createId: 1,
  createDate: new Date,
  updateId: 1,
  updateDate: new Date,
  isDelete: 0,
})
//添加所有详情

let addDetail=async(outStoreCode:string)=>{
  for (const item of OutStoreDetail.value) {
    let response = await request.post('kc/outStoreDetail/addOutStoreDetail', {
      ...item,
      outStoreCode:outStoreCode
    });
  }
}

onMounted(async () => {

  await showOutStore(route.params.code)
})

//回显
let showOutStore=async(code:any)=>{
  //回显入库单
  let response1=await request.post('kc/outStore/getOutStoreList',{
    code:code,
    typeId:34
  })

  outStoreOrder.value = response1.data.data.list[0]
  //回显详情
  let response2 = await request.post('kc/outStoreDetail/getOutStoreDetailList', {
    outStoreCode:code
  },{
    headers:{
      'Content-Type':'application/x-www-form-urlencoded'
    }

  }

  );

  OutStoreDetail.value = response2.data.data
  if(OutStoreDetail.value!=null&&OutStoreDetail.value.length>0){
    OutStoreDetail.value.forEach(item=>{
      changeNum(item)
      storeChange(item)
    })
  }
  console.log(response2.data.data)
}

//动态加载客户
let customerList=ref<Customer[]>([])
let selectCustomer=async()=>{
  let response=await request.post('basic/Customer/selectAllCustomer')
  customerList.value=response.data.data
  console.log(customerList.value)
}
selectCustomer()

let userList=ref<User[]>([])
let selectUser=async()=>{
  let response=await request.post('per/user/getAll')
  userList.value=response.data.data
  console.log(userList.value)
}
selectUser()

let deptList=ref<Department[]>([])
let selectDept=async()=>{
  let response=await request.post('per/dept/getAll')
  deptList.value=response.data.data
  console.log(deptList.value)
}
selectDept()


let storeList=ref<Store[]>([])
let selectStore=async()=>{
  let response=await request.post('basic/store/getAllStore')
  storeList.value=response.data.data
  console.log(storeList.value)
}
selectStore()

const changeNum = (outStoreDetail:any) => {

  outStoreDetail.sumPrice =  parseFloat((outStoreDetail.price * outStoreDetail.count).toFixed(2))
  outStoreDetail.taxSinglePrice =  parseFloat((outStoreDetail.price * (1 + outStoreDetail.tax/100)).toFixed(2))
  outStoreDetail.price =  parseFloat(outStoreDetail.price.toFixed(2))
  outStoreDetail.taxSumPrice =  parseFloat((outStoreDetail.taxSinglePrice *outStoreDetail.count).toFixed(2))
  outStoreDetail.outStoreSingleCost = outStoreDetail.price
  outStoreDetail.outStoreSumCost =  parseFloat((outStoreDetail.price * outStoreDetail.count).toFixed(2))
}


const changePrice = (outStoreDetail:any) => {
  outStoreDetail.sumPrice =  parseFloat((outStoreDetail.price * outStoreDetail.count).toFixed(2))
  outStoreDetail.taxSinglePrice =  parseFloat((outStoreDetail.price * (1 + outStoreDetail.tax/100)).toFixed(2))
  outStoreDetail.price =  parseFloat(outStoreDetail.price.toFixed(2))
  outStoreDetail.taxSumPrice =  parseFloat((outStoreDetail.taxSinglePrice *outStoreDetail.count).toFixed(2))
  outStoreDetail.outStoreSingleCost = outStoreDetail.price
  outStoreDetail.outStoreSumCost =  parseFloat((outStoreDetail.price * outStoreDetail.count).toFixed(2))
}


// 生成uuid
function generateUUID() {
  const min = 100000000;
  const max = 999999999;
  return Math.floor(Math.random() * (max - min + 1)) + min;
}


//入库详情
const OutStoreDetail = ref([{
  id: generateUUID(),
  outStoreCode:'',
  goodId:0,
  goodsCode:'',
  goodsName:'',
  goodsType:'',
  stock:0,
  tax:0,
  count: 0,
  kname:'',
  notes:'',
  storeId:null,
  storeName:'',
  unit:'',
  price:0,
  taxSinglePrice:0,
  taxSumPrice:0,
  sumPrice:0,
  outStoreSingleCost:0,
  outStoreSumCost:0,
  isDelete:0,
  createId:1,
  createDate:new Date(),
  updateId:1,
  updateDate:new Date()
}])




//选中商品数据
const handleGoodsChange = async (row: any) => {
  const selected = goodsList.value.find(item => item.code === row.goodsCode)
  if (selected) {
    row.goodsName = selected.name
    row.goodId = selected.id;
    row.stock = selected.stock
    row.unit = selected.unique
    row.tax = selected.tax;
    row.kname = selected.kname
    calculateTaxPrice(row)
  } else {
    // 清空相关字段
    row.goodsName = ''
    row.unit = '件'
    row.stock = 0
  }

  let response = await request.get('kc/StoreGoodSummary/selectKcStoreGoodBySidCid',{
    params:{
      sid: row.storeId,
      gid: row.goodId
    }
  })

  if (response.data.data) {
    row.stock = response.data.data.stock
    row.outStoreSingleCost = response.data.data.singleCost
  } else {
    row.stock = 0
    row.outStoreSingleCost = 0
  }
  changeNum(row)
}
//选中数组
const newSelectedRows = ref<any[]>([])

// 处理选中行变化
const newHHandleSelectionChange = (selection: any[]) => {
  newSelectedRows.value = selection
}

// 删除选中行方法（添加确认对话框）
const deleteSelectedRows = async () => {
  if (newSelectedRows.value.length === 0) {
    ElMessage.warning('请先选择要删除的行')
    return
  }

  try {
    await ElMessageBox.confirm(
        `确定要删除选中的 ${newSelectedRows.value.length} 行吗？`,
        '删除确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
    )
   // 通过ID过滤实现删除
    const selectedIds = new Set(newSelectedRows.value.map(row => row.id))
    OutStoreDetail.value = OutStoreDetail.value.filter(row => !selectedIds.has(row.id))

    ElMessage.success('删除成功')
  } catch (error) {
    ElMessage.info('已取消删除')
  }
}


//价格校验
const validatePrice = (row:any) => {
  row.price = row.price.replace(/[^\d.]/g, '')
}

// 含税价计算
const calculateTaxPrice = (row:any) => {
  if (row.price && row.tax) {
    row.taxSinglePrice = (row.price * (1 + row.tax/100)).toFixed(2)
  }
}

// //只读队列
// const readonlyColumns = [
//   { prop: 'taxIncludedPrice', label: '含税单价', width: 120 },
//   { prop: 'tax', label: '增值税税率 (%)', width: 150 }
// ]

//格式化金额显示
const totalAmount = computed(() => {
  return OutStoreDetail.value.reduce((sum, row) => {
    const price = Number(row.taxSinglePrice) || 0
    const quantity = Number(row.count) || 0
    return sum + (price * quantity)
  }, 0)
})

//计算总价
const formatTotal = computed(() => {
  return `¥${totalAmount.value.toFixed(2)}`
})



//弹窗的处理
let PopupsPageNo=ref(1)
let PopupsPageSize=ref(10)
const selectedCount = ref(0)
const totalItems = ref(0)
const dialogVisible = ref(false)
const currentSelected = ref(null)//当前选中
const selectedRows = ref([]) // 多选时使用
const searchForm = reactive({
  code: '',
})

// 表格选择处理
const handleSelectionChange = (selection:any) => {
  selectedRows.value = selection
  selectedCount.value = selection.length
  if (selection.length > 0) {
    currentSelected.value = selection[0]
  } else {
    currentSelected.value = null
  }
}



const clearSelection = () => {

}




//多添加一行详情
let addDetailRow = () => {
  OutStoreDetail.value.push({
    id: generateUUID(),
    outStoreCode:'',
    goodId:0,
    goodsCode:'',
    goodsName:'',
    goodsType:'',
    stock:0,
    tax:0,
    count: 0,
    kname:'',
    notes:'',
    storeId:null,
    storeName:'',
    unit:'',
    price:0,
    taxSinglePrice:0,
    taxSumPrice:0,
    sumPrice:0,
    outStoreSingleCost:0,
    outStoreSumCost:0,
    isDelete:0,
    createId:1,
    createDate:new Date(),
    updateId:1,
    updateDate:new Date()
  })
}

const formRef = ref<FormInstance>();
//点击新增后新增入库单
let insertOutStoreOrder =async()=>{

  if (!formRef.value) return;
  await formRef.value.validate(async (valid) => {
    if (!valid) {
      ElMessage.warning('请填写完整基本信息');
      return;
    }
    for (const item of OutStoreDetail.value) {
      if(item.count>item.stock){
        ElMessage.error('出库失败，'+item.goodsName+'商品库存不足以出库')
        return
      }
    }
    await request.get('kc/outStore/delOutStore', {
          params: {
            id: outStoreOrder.value.id,
          }
        },
    )
    if (sourceCode.value != '') {
      outStoreOrder.value.sourceCode = sourceCode.value
    }
    let response = await request.post('kc/outStore/addOutStore', {
          ...outStoreOrder.value,
        },
    )
    await addDetail(outStoreOrder.value.code)
    if (response.data.code == 200) {
      ElMessage.success('修改成功')
    } else {
      ElMessage.error('修改失败')
    }
  })
}



</script>


<style scoped>
.el-row {
  margin-bottom: 20px;
}

.el-row:last-child {
  margin-bottom: 0;
}

.el-col {
  border-radius: 4px;
}

.grid-content {
  border-radius: 4px;
  min-height: 36px;
}
.required-label::after {
  content: "*";
  color: #f56c6c;
  margin-left: 4px;
}

.goods-table {
  margin-top: 20px;
}

.toolbar {
  margin-bottom: 15px;
  padding: 10px;
  background: #f5f7fa;
  border-radius: 4px;
}

.el-table :deep(.el-input__inner) {
  text-align: center;
}
.total-summary {
  background: #fff8dc; /* 浅黄色背景 */
  padding: 12px 20px;
  display: flex;
  justify-content: flex-end;
  border: 1px solid #ebeef5;
  border-top: none;
}

.total-label {
  font-weight: 600;
  color: #606266;
  margin-right: 30px;
}

.total-amount {
  color: #f56c6c;
  min-width: 120px;
  text-align: right;
  font-family: Arial, sans-serif;
}
.pagination-wrapper {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}
.dialog-header {
  margin-top: 10px;
  margin-left: 30px;
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  flex-wrap: wrap;
  gap: 10px;
}

.date-label {
  color: #606266;
  margin: 0 10px;
}

.date-separator {
  margin: 0 8px;
  color: #c0c4cc;
}

.selected-info {
  margin: 12px 0;
  display: flex;
  align-items: center;
  gap: 10px;
  color: #606266;
}

.dialog-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 15px;
}

.pagination-info {
  color: #606266;
}

.action-buttons {
  display: flex;
  gap: 15px;
}

:deep(.el-dialog__header) {
  border-bottom: 1px solid #ebeef5;
}


</style>
